/*!
 * 基础控件类
 * ecp.qzz.date.js
 * 创建：qzz
 * 日期: 2014-03-1
 */
define(["qzz.object"], function() {
	
	var qzz = window.qzz;
	/**
	 * 基础控件类
	 * @class date
	 * @author qinzhenzhou@ygsoft.com
	 * @date 2014.3.1
	 */
	qzz.date = qzz.Class(qzz.object, {
		_create:function(){
			this.className = "Date";
			//月份
			this.months = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
			//月份中文
			this.monthCN = this.getI18n("qzz.monthsText", ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]);
			//季度中文
			this.seasonCN = this.getI18n("qzz.seasonText", ["第一季度", "第二季度", "第三季度", "第四季度"]);
		    //周期类型.
			this.cyctypes = {
		    	second:	"second",
				minute:"minute",
				hour: "hour",
			    day : "day",
			    ten : "ten",
			    month : "month",
			    season : "season",
			    year : "year"
			};
		    this.dateSplit = "-";
		    this.timeSplit = ":";
		    this.dtSplit = /[- ]/g;
		    this.cyctype = this.cyctypes.day;
		    this.showTime = false;
		},
		setShowTime:function(value) {
			if(value == null) {
				value = true;
			}
			this.showTime = value;
		},
	    /**
	     * 日期周期.
	     */
	    setCycType:function(value) {
	    	this.cyctype = value;
	    },
		/**
		 * 是否润年.
		 * @param inYear 年
		 */
	    isLeapYear:function(inYear) {
			if ((inYear % 4 == 0 && !(inYear % 100 == 0)) || inYear % 400 == 0) {
			    return true;
			} else {
			    return false;
			}
		},
		/**
		 * 返回年份框.
		 */
		getYearsRect:function(startYear) {
			var re = [];
			var k = 0;
			if(startYear == null) {
				var d = new Date();
				startYear = d.getFullYear();
			}
			startYear = startYear/10;
			//取整
			isy = parseInt(startYear, 10);
			//判断是否相等
			if(startYear - isy === 0) {
				isy = isy - 1;
			}
			//重新还原值
			startYear = isy * 10;
			
			startYear = parseInt(startYear, 10);
			for(var i = 0; i < 3; i++) {
				var row = [];
				for(var j = 0; j < 4; j++) {
					row.push(startYear + k);
					k++;
				}
				re.push(row);
			}
			return re;
		},
		/**
		 * 返回季度框.
		 */
		getSeasonsRect:function() {
			var re = [];
			var k = 0;
			for(var i = 0; i < 2; i++) {
				var row = [];
				for(var j = 0; j < 2; j++) {					
					row.push(this.seasonCN[k++]);
				}
				re.push(row);
			}
			return re;
		},
		/**
		 * 返回月份框.
		 */
		getMonthsRect:function() {
			var re = [];
			var k = 0;
			for(var i = 0; i < 3; i++) {
				var row = [];
				for(var j = 0; j < 4; j++) {					
					row.push(this.monthCN[k++]);
				}
				re.push(row);
			}
			return re;
		},
		/**
		 * 返回旬，上旬、中旬、下旬.
		 */
		getTensRect:function() {
			
		},
		getSecondsRect:function(hour, minute) {
			var seconds = [];
			var k = 0;
			for(var i = 0; i < 4; i++) {
				var rm = [];
				for(var j = 0; j < 3; j++) {
					var fstr = k;
					if(k == 0 || k == 5) {
						fstr = "0" + k;
					}
					rm.push(hour + ":" + minute + ":" + fstr);
					k = k + 5;
				}
				seconds.push(rm);
			}
			return seconds;
		},
		/**
		 * 返回分钟选择面板.
		 */
		getMinutesRect:function(hour) {
			var minutes = [];
			var k = 0;
			for(var i = 0; i < 3; i++) {
				var rm = [];
				for(var j = 0; j < 4; j++) {
					var fstr = k;
					if(k == 0 || k == 5) {
						fstr = "0" + k;
					}
					rm.push(hour + ":" + fstr);
					k = k + 5;
				}
				minutes.push(rm);
			}
			return minutes;
		},
		/**
		 * 返回小时选择面板.
		 */
		getHoursRect:function() {
			var hours = [];
			var k = 0;
			for(var i = 0; i < 6; i++) {
				var rh = [];
				for(var j = 0; j < 4; j++) {
					rh.push(k + ":00");
					k++;
				}
				hours.push(rh);
			}
			return hours;
		},
		/**
		 * 返回日期框.
		 * @param year 年
		 * @param month 月
		 * @param other 是否返回其它月份的日期
		 */
		getDaysRect:function(year, month, other) {
			var mdays = [];
			var firstDate = new Date(year, month - 1, 1);
			var curWeek = firstDate.getDay();
			firstDate = null;
			var cmds = this.getMonthDays(year, month);
			var py = year,pm = month - 1;
			if(pm < 1) {
				py --;
				pm = 12;
			}
			var pmds = this.getMonthDays(py, pm);
			var ps = pmds - curWeek + 1;
			var isInit = false;
			var k = 1, o = 1;
			for(var i = 0; i < 6; i++) {
				var cd = [];
				for(var j = 0; j < 7; j++) {
					if(i == 0 && j == curWeek) {
						cd[j] = k++;
						isInit = true;
					} else if(isInit) {
						if(k <= cmds) {
						    cd[j] = k++;
						} else if(other === true) {
							cd[j] = o++;
						}
					} else {
						//月初其它月末
						cd[j] = ps++;
					}
				}
				mdays.push(cd);
			}
			return mdays;
		},
		/**
		 * 获取某月天数.
		 * @param year 年
		 * @param month 月
		 * @return 返回
		 */
	    getMonthDays:function(year, month) {
	    	if(month == null) {
	    		month = 1;
	    	}
	    	if(month < 1) {
	    		month = 1;
	    	}
	    	if(month > 12) {
	    		month = 12;
	    	}
	        if (month != 2) {
	            return this.months[month - 1];
	        } else {
	        	if(year == null) {
	        		var d = new Date();
	        		year = d.getFullYear();
	        	}
	            if (this.isLeapYear(year)) {
	                return this.months[1] + 1;
	            } else {
	                return this.months[1];
	            }
	        }
	    },
	    /**
	     * 获取时间.
	     */
	    _getCurTime:function(date) {
	    	var zero = "0";
	    	var d = date;
	    	if(d == null) {
    		    d = new Date();
	    	}
    		var tmh = d.getHours();
			if(tmh < 10) {
				tmh = zero + tmh;
			}
			var tmm = d.getMinutes();
			if(tmm < 10) {
				tmm = zero + tmm;
			}
			var tms = d.getSeconds();
			if(tms < 10) {
				tms = zero + tms;
			}
			return {"h":tmh,"m":tmm,"s":tms};
	    },
	    /**
		 * 日期转换成字符串.
		 */
	    _dateToStr:function(year, month, day) {
	        var zero = "0";
	        var split = this.dateSplit;
	    	if(month < 1) {
	        	month = 1;
	        }
	        if(month > 12) {
	        	month = 12;
	        }	        
	        if(day < 1) {
	        	day = 1;
	        }
	        maxDay = this.getMonthDays(year, month);  
	        if(day > maxDay) {
	        	day = maxDay;
	        }
	        //处理超出范围的情况.	        
	        if (year < 1000) {
	            year = 2000 + year;
	    	}
	        if(month < 10) {
	            month = zero + month;
	        }            	                    
	        if(day < 10) {
	        	day = zero + day;
	        }	        
	        return year + split + month + split + day;
	    },
	    /**
	     * 转换到日期.
	     * @param value 日期.
	     */
	    toDate:function(value) {
	    	var rs = "";
	    	var zero = "0";
	        var split = this.dateSplit;
	    	if(!isNaN(value)) {
	    		var d = new Date(value);
	    		var m = d.getMonth() + 1;
	    		if(m < 10) {
	    			m = zero + m;
	    		}
	    		var ds = d.getDate();
	    		if(ds < 10) {
	    			ds = zero + ds;
	    		}
	    		rs = d.getFullYear();
	    		rs += split;
	    		rs += m;
                if(this.cyctype !== this.cyctypes.month) {
		    		rs += split
		    		rs += ds;
                }
	    		if(this.cyctype === this.cyctypes.day && this.showTime) {
	    			rs += " ";
	    			var ctm = this._getCurTime(d);
	    			rs += ctm.h;
	    			rs += this.timeSplit;
	    			rs += ctm.m;
	    			rs += this.timeSplit;
	    			rs += ctm.s;
	    		}
	    		d = null;
	    	} else {
	    		rs = this.checkDate(value);
	    		if(this.cyctype === this.cyctypes.year) {
	    			var rsAry = rs.split(split);
	    			rs = rsAry[0];
	    			rsAry = null;
	    		} else if(this.cyctype === this.cyctypes.month) {
	    			var rsAry = rs.split(split);
	    			rs = rsAry[0] + split + rsAry[1];
	    			rsAry = null;
	    		}
	    	}
	    	return rs;
	    },
	    /**
	     * 日期合法性检查.
	     * @param date 日期
	     */
	    checkDate:function(date){
	    	var vlstr = date;
	    	if(typeof vlstr != "string") return "";
	    	var siAry = vlstr.split(" ");
	        if (siAry.length > 0) {
	            vlstr = siAry[0];
	        }
	        var split = this.dateSplit;
	        //格式转换
	        vlstr = vlstr.replace(/([\.\\\/])/g, split);
	        if (isNaN(vlstr)) {
	        	//带分隔符转换
	            var aryd = vlstr.split(split);
	            if(this.cyctype == this.cyctypes.month && aryd.length == 2) {
	            	aryd.push("01");
	            } else if(this.cyctype == this.cyctypes.season) {
	            	if(aryd.length < 2) {
						//文本转换成季度第一个月
		            	aryd = siAry;
		            	aryd[0] = aryd[0].replace(this.getI18n("qzz.year","年"), "");
	            		var len = this.seasonCN.length;
						//找到季度序号
	            		var season = -1;
	            		for(var i = 0; i < len; i++) {
	            			if(aryd[1] === this.seasonCN[i]) {
	            				season = i;
	            				break;
	            			}
	            		}
						//转换成月份
	            		if(season >= 0) {
	            			aryd[1] = this.getMonthBySeason(season + 1);
	            			if(aryd[1] < 10) {
	            				aryd[1] = "0" + aryd[1];
	            			}
	            		}
						//添加日
	            		aryd.push("01");
	            	}
	            }
	            if (aryd.length == 3) {
	                if (!isNaN(aryd[0]) && !isNaN(aryd[1]) && !isNaN(aryd[2])) {
	                    var year = parseInt(aryd[0], 10);
	                    var month = parseInt(aryd[1], 10);
	                    var day = parseInt(aryd[2], 10);
	                    vlstr = this._dateToStr(year, month, day);
	                }
	            }
	            aryd = null;
	        } else {
	        	//数值格式转换
	            var dateStr = vlstr.replace(/[^0-9]/, "");
	            var dlen = dateStr.length;
	            if(dlen < 7) {
	            	if(this.cyctype === this.cyctypes.year) {
	            		dateStr += "0101";
	            	} else if(this.cyctype === this.cyctypes.month) {
	            	    dateStr += "01";
	            	}
	            }
	            dlen = dateStr.length;
	            var vlstr = "";
	            if (dlen == 8) {
	                var year = parseInt(dateStr.substr(0, 4), 10);
	                var month = parseInt(dateStr.substr(4, 2), 10);
	                var day = parseInt(dateStr.substr(6, 2), 10);
	                vlstr = this._dateToStr(year, month, day);
	            } else if (dlen == 6) {
	                var year = parseInt("20" + dateStr.substr(0, 2), 10);
	                var month = parseInt(dateStr.substr(2, 2), 10);
	                var day = parseInt(dateStr.substr(4, 2), 10);
	                vlstr = this._dateToStr(year, month, day);
	            }
	        }
	        if(vlstr !== "" && (this.cyctype === this.cyctypes.day &&  this.showTime === true 
	        		|| this.cyctype === this.cyctypes.hour 
	        		    || this.cyctype === this.cyctypes.minute
	        		        || this.cyctype === this.cyctypes.second)) {
	        	var tmh, tmm, tms;
	        	var ht = false;
	        	if(siAry.length > 1) {
		        	tmstr = siAry[1];
		        	tmAry = tmstr.split(/[:.]/g);		        	
		        	if(tmAry.length > 2) {
		        		tmh = tmAry[0];
		        		tmm = tmAry[1];
		        		tms = tmAry[2];
		        		ht = true;
		        	}
	        	} 
	        	if(!ht) {
	        		var ctm = this._getCurTime();
	        		tmh = ctm.h;
	        		tmm = ctm.m;
	        		tms = ctm.s;
	        	}
	        	vlstr += " " + tmh + this.timeSplit + tmm + this.timeSplit + tms;
	        }
	        if (vlstr.length > 0) {
	           return vlstr;
	        } else {
	            return "";
	        }
	    },
        strToTimeMillis : function(str){
        	if(!str){
        		return 0;
        	}else if(str.indexOf(".")!==-1){
        		//此方法不支持毫秒，去掉毫秒部分
        		str = str.substring(0,str.indexOf("."));
        	}
        	return +new Date(this.formatDate(str).replace(/-/g,"/"));
        },
        formatDate : function(str){
        	var reg = /^\d{4}[-\/]\d{2}$/,
        		reg1 = /^\d{4}$/;
        	if (reg.test(str)){
        		str += "-01";
        	} else if (reg1.test(str)){
        		str += "-01-01";
        	}
        	return str;        	
        },
	    parseEcpDate : function(value){
        	if (arguments.length){
        		if (value === ""){
        			return value;
        		}
        		var timeMillis = this.strToTimeMillis(value);
        		timeMillis = isNaN(timeMillis)?(+new Date()) : timeMillis; 
        		return "\/Date(" + timeMillis + "+0800)\/";
        	}
        	return "\/Date(" + +new Date() + "+0800)\/";
        },
        invalidDate : function(dateStr) {
        	var ds = dateStr.replace(/^(\d{4})(\d{2})?(\d{2})?$/g, function(){
	            var y = RegExp.$1,
	            	m = RegExp.$2,
	            	d = RegExp.$3;
	            	
	            return   y + "-" + (m ? m : "01" ) + "-" + (d ? d : "01" );
            });
        	var dt = new Date(ds);
            return (dt).valueOf().toString() === "NaN" ? true : ds;
        },
        parseDate: function(str, reg){
        	if(str === "" || str === null || str === undefined){
        		return +new Date();
        	}  
        	if(typeof str === "number" || $.type(str) === "date"){
        		return +str;
        	}
            if (typeof str === "string"){
        		var dt = this.invalidDate(str);
        		if(typeof dt === "string") {
        			return +new Date(dt);
        		}
        	}
        	var d = this.strToTimeMillis(str);
        	// 判断字符串是否为数值
        	if (!isNaN(d)){
        		return d;
        	}
        	var reg = reg ? reg : /\b\((\-*\d*)\+\b/,        	
        		arr = str.toString().match(reg);
        	return arr ? arr[1] : +new Date();        			
        },
        strToDate: function (str, showTime, showType,showSeconds) {
            if (str === undefined || str ===null || str ==="") {
                return "";
            }
            str = this.parseDate(str);
            var d = !isNaN(str) ? new Date(+str) : new Date(),
				month = d.getMonth() + 1,
				day = d.getDate(),
				hours = d.getHours(),
				minutes = d.getMinutes(),
				seconds = d.getSeconds(),
				time = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes);
			if(showSeconds) {
				time += ":" + (seconds < 10 ? "0" + seconds : seconds);
			}
            if(showType == "Y" || showType == "year") {
            	return d.getFullYear();
            } else if(showType == "M" || showType == "month" || showType == "S" || showType == "season") {
            	return d.getFullYear() + "-" + (month < 10 ? "0" + month : month);            	
            }
            return d.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + (showTime ? " " + time : "");
        },
        /**
         * 通过月份获取对应的季度.
         */
        getSeasonByMonth:function(month) {
        	var res = 1;
        	if(month <= 3) {
        		res = 1;
        	} else if(month <= 6) {
        		res = 2;
        	} else if(month <= 9) {
        		res = 3;
        	} else {
        		res = 4;
        	}
        	return res;        	
        },
        /**
         * 通过季度获取月份.
         */
        getMonthBySeason:function(season) {
        	var res = 1;
        	switch(season) {
        	    case 1: res = 1; break;
        	    case 2: res = 4; break;
        	    case 3: res = 7; break;
        	    case 4: res = 10; break;
        	}
        	return res;
        },
        /**
         * 格式化显示数据.
         * @param val 传入完整的日期
         * @return 返回格式化后的日期，如 2017-01-01 
         *     如果周期是year则返回2017, 
         *     周期是season则返回2017年 第一季度
         *     周期是month 是返回2017-01
         */
        getFormatDate:function(val) {
	    	if(this.cyctype === this.cyctypes.year) {
	    	    var dtAry = val.split("-");
	    	    val = dtAry[0];
	    	} else if(this.cyctype === this.cyctypes.season) {
	        	var dtAry = val.split("-");
	        	//输入非法值控制
	        	var nw = new Date();
	        	var year = dtAry[0];
	        	if(isNaN(year)) {
	        		year = (year + "").replace(/[^0-9]/g, "");
	        		if(year === "") {
	        		    year = nw.getFullYear();
	        		}
	        	}
	        	if(isNaN(dtAry[1])) {	        		
	        		dtAry[1] = nw.getMonth() + 1;
	        	}
    			val = year + this.getI18n("qzz.year", "年") + " " 
    			    + this.seasonCN[this.getSeasonByMonth(parseInt(dtAry[1], 10)) - 1];
	        } else if(this.cyctype === this.cyctypes.month) {
	        	var dtAry = val.split("-");
    		    val = dtAry[0] + "-" + dtAry[1];
	        }
	    	return val;
        }
	});	
    return qzz.date;
});